/**
 * @file image_process.c
 * @brief 图像处理模块实现
 * @version 2.1
 * @date 2023-05-20
 * 
 * 注意：此文件已经适配RK3588平台，可以在没有OpenCV的情况下降级使用
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <stdbool.h>
#include "image_process.h"
#include "system_utils.h"

// 根据编译选项决定是否使用OpenCV
#ifdef HAVE_OPENCV
// 声明OpenCV包装函数
#ifdef __cplusplus
// 在C++环境中，直接包含OpenCV头文件
#include <opencv2/opencv.hpp>
#else
// 在C环境中，只声明函数原型
bool opencv_resize_image(const unsigned char* src_data, int src_width, int src_height, int src_channels,
                        unsigned char* dst_data, int dst_width, int dst_height);

void opencv_grayscale_image(const unsigned char* src_data, int src_width, int src_height, int src_channels,
                          unsigned char* dst_data);

void opencv_blur_image(const unsigned char* src_data, int src_width, int src_height, int src_channels,
                      unsigned char* dst_data, int kernel_size);

bool opencv_detect_edges(const unsigned char* src_data, int src_width, int src_height,
                        unsigned char* dst_data, int threshold_value);

bool opencv_find_contours(const unsigned char* src_data, int src_width, int src_height,
                        ImageContour* contours, int max_contours, int* num_contours);

bool opencv_draw_contours(unsigned char* image_data, int width, int height, int channels,
                        const ImageContour* contours, int num_contours, 
                        unsigned char b, unsigned char g, unsigned char r, unsigned char a);
#endif
#else
// 无OpenCV支持，使用基本图像处理
#define NO_OPENCV_SUPPORT
#endif

// 全局图像处理器配置
static ImageProcessorConfig g_config = {0};

// 图像处理器状态
static struct {
    bool initialized;          // 是否初始化
    bool adaptive_threshold;   // 是否启用自适应阈值
    bool dynamic_blur;         // 是否启用动态模糊
    int histogram[256];        // 灰度直方图
    float avg_light_level;     // 平均亮度水平
    int processing_level;      // 处理复杂度级别(1-3)
    bool debug_mode;           // 调试模式
} g_image_processor = {0};

// 静态缓冲区池，用于减少频繁的内存分配和释放
#define MAX_BUFFER_POOL_SIZE 4  // 最大缓冲区数量
static struct {
    unsigned char *buffers[MAX_BUFFER_POOL_SIZE];
    size_t buffer_sizes[MAX_BUFFER_POOL_SIZE];
    bool in_use[MAX_BUFFER_POOL_SIZE];
    bool initialized;
} g_buffer_pool = {0};

// 指数查找表，用于加速计算
#define EXP_LUT_SIZE 1024
#define EXP_LUT_SCALE 8.0f  // 缩放因子
static float g_exp_lut[EXP_LUT_SIZE];
static bool g_exp_lut_initialized = false;

// 前向声明内部函数
static bool resize_image(const Image *src, Image *dst, int width, int height);
static void grayscale_image(const Image *src, Image *dst);
static void blur_image(const Image *src, Image *dst, int kernel_size);
static bool detect_edges(const Image *src, Image *dst, int threshold_value);
static bool find_contours(const Image *src, ImageContour *contours, int max_contours, int *num_contours);
static bool measure_object(const ImageContour *contour, float *width, float *height);
static bool draw_contours(Image *image, const ImageContour *contours, int num_contours, Colour colour);

// 缓冲区管理函数前向声明
static void init_buffer_pool(void);
static unsigned char *get_buffer(size_t size);
static void release_buffer(unsigned char *buffer);
static void cleanup_buffer_pool(void);

// 无OpenCV情况下的简单模拟实现
#ifdef NO_OPENCV_SUPPORT
/**
 * @brief 模拟边缘检测 - 简单的Sobel算子实现
 * 
 * @param src 源图像
 * @param dst 目标图像
 */
static void simulate_edge_detection(const Image *src, Image *dst) {
    int width = src->width;
    int height = src->height;
    
    // 创建临时缓冲区
    unsigned char *temp = get_buffer(width * height);
    if (!temp) {
        return;
    }
    
    memcpy(temp, src->data, width * height);
    
    // Sobel算子
    int sobel_x[3][3] = {{-1, 0, 1}, {-2, 0, 2}, {-1, 0, 1}};
    int sobel_y[3][3] = {{-1, -2, -1}, {0, 0, 0}, {1, 2, 1}};
    
    for (int y = 1; y < height - 1; y++) {
        for (int x = 1; x < width - 1; x++) {
            int gx = 0, gy = 0;
            
            // 应用Sobel算子
            for (int ky = -1; ky <= 1; ky++) {
                for (int kx = -1; kx <= 1; kx++) {
                    int pixel = temp[(y + ky) * width + (x + kx)];
                    gx += pixel * sobel_x[ky + 1][kx + 1];
                    gy += pixel * sobel_y[ky + 1][kx + 1];
                }
            }
            
            // 计算梯度幅值
            int magnitude = (int)sqrt(gx * gx + gy * gy);
            
            // 阈值化
            dst->data[y * width + x] = (magnitude > 50) ? 255 : 0;
        }
    }
    
    release_buffer(temp);
}

/**
 * @brief 模拟轮廓检测 - 非常简化的实现
 * 
 * @param binary_image 二值化图像
 * @param contours 轮廓数组
 * @param max_contours 最大轮廓数
 * @param num_contours 输出的轮廓数
 */
static void simulate_contour_detection(Image *binary_image, ImageContour *contours, int max_contours, int *num_contours) {
    int width = binary_image->width;
    int height = binary_image->height;
    
    // 查找连通区域的简化版本
    // 这里我们只是模拟，寻找一些白色像素区域作为"轮廓"
    
    // 标记已访问的像素
    bool *visited = (bool *)calloc(width * height, sizeof(bool));
    if (!visited) {
        *num_contours = 0;
        return;
    }
    
    *num_contours = 0;
    
    // 扫描图像找连通区域
    for (int y = 0; y < height && *num_contours < max_contours; y++) {
        for (int x = 0; x < width && *num_contours < max_contours; x++) {
            int idx = y * width + x;
            
            // 如果是白色像素且未访问过
            if (binary_image->data[idx] == 255 && !visited[idx]) {
                // 找到一个新轮廓起点
                int min_x = x, min_y = y, max_x = x, max_y = y;
                int area = 0;
                
                // 简单的广度优先搜索来查找连通区域
                int queue_size = width * height;
                int *queue_x = (int *)malloc(queue_size * sizeof(int));
                int *queue_y = (int *)malloc(queue_size * sizeof(int));
                
                if (!queue_x || !queue_y) {
                    if (queue_x) free(queue_x);
                    if (queue_y) free(queue_y);
                    free(visited);
                    *num_contours = 0;
                    return;
                }
                
                int queue_start = 0, queue_end = 0;
                
                // 添加起始点到队列
                queue_x[queue_end] = x;
                queue_y[queue_end] = y;
                queue_end++;
                visited[idx] = true;
                area++;
                
                // 广度优先搜索
                while (queue_start < queue_end) {
                    int cx = queue_x[queue_start];
                    int cy = queue_y[queue_start];
                    queue_start++;
                    
                    // 检查邻居
                    const int dx[4] = {1, 0, -1, 0};
                    const int dy[4] = {0, 1, 0, -1};
                    
                    for (int i = 0; i < 4; i++) {
                        int nx = cx + dx[i];
                        int ny = cy + dy[i];
                        
                        // 检查边界
                        if (nx >= 0 && nx < width && ny >= 0 && ny < height) {
                            int nidx = ny * width + nx;
                            
                            // 如果是白色像素且未访问过
                            if (binary_image->data[nidx] == 255 && !visited[nidx]) {
                                queue_x[queue_end] = nx;
                                queue_y[queue_end] = ny;
                                queue_end++;
                                visited[nidx] = true;
                                area++;
                                
                                // 更新边界框
                                if (nx < min_x) min_x = nx;
                                if (ny < min_y) min_y = ny;
                                if (nx > max_x) max_x = nx;
                                if (ny > max_y) max_y = ny;
                            }
                        }
                    }
                }
                
                free(queue_x);
                free(queue_y);
                
                // 添加轮廓信息
                contours[*num_contours].x = min_x;
                contours[*num_contours].y = min_y;
                contours[*num_contours].width = max_x - min_x + 1;
                contours[*num_contours].height = max_y - min_y + 1;
                contours[*num_contours].area = area;
                
                (*num_contours)++;
            }
        }
    }
    
    free(visited);
}
#endif

/**
 * @brief 初始化指数查找表
 */
static void init_exp_lut(void) {
    if (!g_exp_lut_initialized) {
        for (int i = 0; i < EXP_LUT_SIZE; i++) {
            float x = (float)i / (EXP_LUT_SIZE - 1) * EXP_LUT_SCALE;
            g_exp_lut[i] = expf(-x);
        }
        g_exp_lut_initialized = true;
        log_message(LOG_LEVEL_DEBUG, "图像处理: 指数查找表已初始化");
    }
}

/**
 * @brief 使用查找表快速计算e^(-x)
 * 
 * @param x 输入值
 * @return float 近似的e^(-x)
 */
static float fast_exp(float x) {
    if (x < 0) return 1.0f;
    if (x >= EXP_LUT_SCALE) return 0.0f;
    
    float idx = x * (EXP_LUT_SIZE - 1) / EXP_LUT_SCALE;
    int idx_floor = (int)idx;
    float frac = idx - idx_floor;
    
    if (idx_floor >= EXP_LUT_SIZE - 1) 
        return g_exp_lut[EXP_LUT_SIZE - 1];
    
    // 线性插值
    return g_exp_lut[idx_floor] * (1.0f - frac) + g_exp_lut[idx_floor + 1] * frac;
}

/**
 * @brief 初始化图像处理模块
 * 
 * @return int 成功返回0，失败返回非0
 */
int init_image_process(void) {
    if (g_image_processor.initialized) {
        log_message(LOG_LEVEL_INFO, "图像处理: 已经初始化");
        return 0;
    }
    
    // 初始化指数查找表
    init_exp_lut();
    
    // 初始化缓冲区池
    init_buffer_pool();
    
    // 设置默认配置
    g_image_processor.initialized = true;
    g_image_processor.adaptive_threshold = true;
    g_image_processor.dynamic_blur = true;
    g_image_processor.avg_light_level = 127.0f;
    g_image_processor.processing_level = 3;
    g_image_processor.debug_mode = false;
    
    g_config.threshold_value = 128;
    g_config.blur_size = 3;
    g_config.min_contour_area = 100;
    g_config.max_contour_area = 50000;
    g_config.pixels_per_mm = 10.0f;  // 默认值，应该根据相机标定调整
    g_config.cable_width_mm = 10.0f; // 默认值，应该根据实际导线规格调整
    
    log_message(LOG_LEVEL_INFO, "图像处理: 初始化成功");
    return 0;
}

/**
 * @brief 清理图像处理模块
 */
void cleanup_image_process(void) {
    // 清理缓冲区池
    cleanup_buffer_pool();
    
    // 重置配置
    g_image_processor.initialized = false;
    
    log_message(LOG_LEVEL_INFO, "图像处理: 资源已清理");
}

/**
 * @brief 缩放图像
 * 
 * @param src 源图像
 * @param dst 目标图像
 * @param width 目标宽度
 * @param height 目标高度
 * @return bool 成功返回true，失败返回false
 */
static bool resize_image(const Image *src, Image *dst, int width, int height) {
    if (!src || !src->data || !dst || !dst->data || 
        width <= 0 || height <= 0 || 
        src->width <= 0 || src->height <= 0) {
        return false;
    }
    
    // 如果需要，调整目标图像大小
    if (dst->width != width || dst->height != height) {
        destroy_image(dst);
        if (create_image(dst, width, height, src->channels) != 0) {
            return false;
        }
    }
    
#ifdef HAVE_OPENCV
    // 使用OpenCV实现
    return opencv_resize_image(src->data, src->width, src->height, src->channels,
                              dst->data, dst->width, dst->height);
#else
    // 简单的最邻近缩放实现
    float x_ratio = (float)src->width / width;
    float y_ratio = (float)src->height / height;
    
    for (int y = 0; y < height; y++) {
        int sy = (int)(y * y_ratio);
        for (int x = 0; x < width; x++) {
            int sx = (int)(x * x_ratio);
            for (int c = 0; c < src->channels; c++) {
                dst->data[(y * width + x) * dst->channels + c] = 
                    src->data[(sy * src->width + sx) * src->channels + c];
            }
        }
    }
    return true;
#endif
}

/**
 * @brief 转换为灰度图
 * 
 * @param src 源图像
 * @param dst 目标图像
 */
static void grayscale_image(const Image *src, Image *dst) {
    if (!src || !src->data || !dst || !dst->data || 
        src->width != dst->width || src->height != dst->height ||
        dst->channels != 1) {
        return;
    }
    
#ifdef HAVE_OPENCV
    // 使用OpenCV实现
    opencv_grayscale_image(src->data, src->width, src->height, src->channels, dst->data);
#else
    // 简单的灰度转换实现
    int pixels = src->width * src->height;
    for (int i = 0; i < pixels; i++) {
        int offset = i * src->channels;
        if (src->channels == 1) {
            dst->data[i] = src->data[offset];
        } else if (src->channels == 3 || src->channels == 4) {
            // 使用BT.709灰度转换系数
            dst->data[i] = (unsigned char)(
                0.2126f * src->data[offset + 2] +  // R
                0.7152f * src->data[offset + 1] +  // G
                0.0722f * src->data[offset]        // B
            );
        }
    }
#endif
}

/**
 * @brief 对图像进行模糊处理
 * 
 * @param src 源图像
 * @param dst 目标图像
 * @param kernel_size 模糊核大小
 */
static void blur_image(const Image *src, Image *dst, int kernel_size) {
    if (!src || !src->data || !dst || !dst->data || 
        src->width != dst->width || src->height != dst->height ||
        src->channels != dst->channels || kernel_size <= 0) {
        return;
    }
    
#ifdef HAVE_OPENCV
    // 使用OpenCV实现
    opencv_blur_image(src->data, src->width, src->height, src->channels, 
                     dst->data, kernel_size);
#else
    // 简单的均值模糊实现
    int half_size = kernel_size / 2;
    int width = src->width;
    int height = src->height;
    int channels = src->channels;
    
    // 创建临时缓冲区以避免原位模糊造成的问题
    unsigned char *temp = get_buffer(width * height * channels);
    if (!temp) {
        memcpy(dst->data, src->data, width * height * channels);
        return;
    }
    
    // 复制原始数据
    memcpy(temp, src->data, width * height * channels);
    
    for (int y = 0; y < height; y++) {
        for (int x = 0; x < width; x++) {
            for (int c = 0; c < channels; c++) {
                int sum = 0;
                int count = 0;
                
                // 计算内核区域内的像素平均值
                for (int ky = -half_size; ky <= half_size; ky++) {
                    int sy = y + ky;
                    if (sy < 0 || sy >= height) continue;
                    
                    for (int kx = -half_size; kx <= half_size; kx++) {
                        int sx = x + kx;
                        if (sx < 0 || sx >= width) continue;
                        
                        sum += temp[(sy * width + sx) * channels + c];
                        count++;
                    }
                }
                
                // 写入平均值
                if (count > 0) {
                    dst->data[(y * width + x) * channels + c] = (unsigned char)(sum / count);
                } else {
                    dst->data[(y * width + x) * channels + c] = temp[(y * width + x) * channels + c];
                }
            }
        }
    }
    
    // 释放临时缓冲区
    release_buffer(temp);
#endif
}

/**
 * @brief 边缘检测/二值化处理
 * 
 * @param src 源图像
 * @param dst 目标图像
 * @param threshold_value 阈值
 * @return bool 成功返回true，失败返回false
 */
static bool detect_edges(const Image *src, Image *dst, int threshold_value) {
    if (!src || !src->data || !dst || !dst->data || 
        src->width != dst->width || src->height != dst->height ||
        src->channels != 1 || dst->channels != 1) {
        return false;
    }
    
#ifdef HAVE_OPENCV
    // 使用OpenCV实现
    return opencv_detect_edges(src->data, src->width, src->height, dst->data, threshold_value);
#else
    // 使用简单模拟实现
    simulate_edge_detection(src, dst);
    return true;
#endif
}

/**
 * @brief 查找轮廓
 * 
 * @param src 源图像
 * @param contours 轮廓数组
 * @param max_contours 最大轮廓数
 * @param num_contours 输出的轮廓数
 * @return bool 成功返回true，失败返回false
 */
static bool find_contours(const Image *src, ImageContour *contours, int max_contours, int *num_contours) {
    if (!src || !src->data || !contours || max_contours <= 0 || !num_contours) {
        return false;
    }
    
#ifdef HAVE_OPENCV
    // 使用OpenCV实现
    return opencv_find_contours(src->data, src->width, src->height, 
                              contours, max_contours, num_contours);
#else
    // 使用简单模拟实现
    *num_contours = 0;
    
    // 创建临时图像
    Image binary_image;
    if (create_image(&binary_image, src->width, src->height, 1) != 0) {
        return false;
    }
    
    // 复制源图像
    memcpy(binary_image.data, src->data, src->width * src->height);
    
    // 调用模拟轮廓检测
    simulate_contour_detection(&binary_image, contours, max_contours, num_contours);
    
    // 清理临时图像
    destroy_image(&binary_image);
    
    return *num_contours > 0;
#endif
}

/**
 * @brief 测量物体尺寸
 * 
 * @param contour 轮廓
 * @param width 输出宽度
 * @param height 输出高度
 * @return bool 成功返回true，失败返回false
 */
static bool measure_object(const ImageContour *contour, float *width, float *height) {
    if (!contour || !width || !height) {
        return false;
    }
    
    *width = contour->width;
    *height = contour->height;
    
    return true;
}

/**
 * @brief 在图像上绘制轮廓
 * 
 * @param image 目标图像
 * @param contours 轮廓数组
 * @param num_contours 轮廓数量
 * @param colour 颜色
 * @return bool 成功返回true，失败返回false
 */
static bool draw_contours(Image *image, const ImageContour *contours, int num_contours, Colour colour) {
    if (!image || !image->data || !contours || num_contours <= 0) {
        return false;
    }
    
#ifdef HAVE_OPENCV
    // 使用OpenCV实现
    return opencv_draw_contours(image->data, image->width, image->height, image->channels,
                              contours, num_contours, 
                              colour.b, colour.g, colour.r, colour.a);
#else
    // 简单实现 - 只绘制边界框
    for (int i = 0; i < num_contours; i++) {
        int x1 = contours[i].x;
        int y1 = contours[i].y;
        int x2 = contours[i].x + contours[i].width;
        int y2 = contours[i].y + contours[i].height;
        
        // 确保坐标在图像范围内
        if (x1 < 0) x1 = 0;
        if (y1 < 0) y1 = 0;
        if (x2 >= image->width) x2 = image->width - 1;
        if (y2 >= image->height) y2 = image->height - 1;
        
        // 绘制边界框
        for (int x = x1; x <= x2; x++) {
            // 上边界和下边界
            for (int y = y1; y <= y1 + 1; y++) {
                if (y >= 0 && y < image->height) {
                    int offset = (y * image->width + x) * image->channels;
                    if (image->channels >= 1) image->data[offset] = colour.b;
                    if (image->channels >= 2) image->data[offset + 1] = colour.g;
                    if (image->channels >= 3) image->data[offset + 2] = colour.r;
                    if (image->channels >= 4) image->data[offset + 3] = colour.a;
                }
            }
            for (int y = y2 - 1; y <= y2; y++) {
                if (y >= 0 && y < image->height) {
                    int offset = (y * image->width + x) * image->channels;
                    if (image->channels >= 1) image->data[offset] = colour.b;
                    if (image->channels >= 2) image->data[offset + 1] = colour.g;
                    if (image->channels >= 3) image->data[offset + 2] = colour.r;
                    if (image->channels >= 4) image->data[offset + 3] = colour.a;
                }
            }
        }
        
        for (int y = y1; y <= y2; y++) {
            // 左边界和右边界
            for (int x = x1; x <= x1 + 1; x++) {
                if (x >= 0 && x < image->width) {
                    int offset = (y * image->width + x) * image->channels;
                    if (image->channels >= 1) image->data[offset] = colour.b;
                    if (image->channels >= 2) image->data[offset + 1] = colour.g;
                    if (image->channels >= 3) image->data[offset + 2] = colour.r;
                    if (image->channels >= 4) image->data[offset + 3] = colour.a;
                }
            }
            for (int x = x2 - 1; x <= x2; x++) {
                if (x >= 0 && x < image->width) {
                    int offset = (y * image->width + x) * image->channels;
                    if (image->channels >= 1) image->data[offset] = colour.b;
                    if (image->channels >= 2) image->data[offset + 1] = colour.g;
                    if (image->channels >= 3) image->data[offset + 2] = colour.r;
                    if (image->channels >= 4) image->data[offset + 3] = colour.a;
                }
            }
        }
    }
    
    return true;
#endif
}

/**
 * @brief 初始化缓冲区池
 */
static void init_buffer_pool(void) {
    if (!g_buffer_pool.initialized) {
        // 初始化缓冲区池
        memset(&g_buffer_pool, 0, sizeof(g_buffer_pool));
        g_buffer_pool.initialized = true;
        log_message(LOG_LEVEL_DEBUG, "图像处理: 缓冲区池已初始化");
    }
}

/**
 * @brief 从缓冲区池获取缓冲区
 * 
 * @param size 所需缓冲区大小
 * @return unsigned char* 缓冲区指针，失败返回NULL
 */
static unsigned char *get_buffer(size_t size) {
    if (!g_buffer_pool.initialized) {
        init_buffer_pool();
    }
    
    // 首先尝试查找现有的可用缓冲区
    for (int i = 0; i < MAX_BUFFER_POOL_SIZE; i++) {
        if (!g_buffer_pool.in_use[i] && 
            g_buffer_pool.buffers[i] && 
            g_buffer_pool.buffer_sizes[i] >= size) {
            // 标记为使用中
            g_buffer_pool.in_use[i] = true;
            return g_buffer_pool.buffers[i];
        }
    }
    
    // 查找空闲槽位
    for (int i = 0; i < MAX_BUFFER_POOL_SIZE; i++) {
        if (!g_buffer_pool.buffers[i]) {
            // 分配新缓冲区
            g_buffer_pool.buffers[i] = (unsigned char *)malloc(size);
            if (g_buffer_pool.buffers[i]) {
                g_buffer_pool.buffer_sizes[i] = size;
                g_buffer_pool.in_use[i] = true;
                return g_buffer_pool.buffers[i];
            }
            return NULL;
        }
    }
    
    // 如果没有可用的槽位，则直接分配
    return (unsigned char *)malloc(size);
}

/**
 * @brief 释放缓冲区回池
 * 
 * @param buffer 要释放的缓冲区指针
 */
static void release_buffer(unsigned char *buffer) {
    if (!buffer || !g_buffer_pool.initialized) {
        return;
    }
    
    // 查找缓冲区在池中的位置
    for (int i = 0; i < MAX_BUFFER_POOL_SIZE; i++) {
        if (g_buffer_pool.buffers[i] == buffer) {
            // 标记为未使用
            g_buffer_pool.in_use[i] = false;
            return;
        }
    }
    
    // 如果不在池中，则直接释放
    free(buffer);
}

/**
 * @brief 清理缓冲区池
 */
static void cleanup_buffer_pool(void) {
    if (!g_buffer_pool.initialized) {
        return;
    }
    
    // 释放所有缓冲区
    for (int i = 0; i < MAX_BUFFER_POOL_SIZE; i++) {
        if (g_buffer_pool.buffers[i]) {
            free(g_buffer_pool.buffers[i]);
            g_buffer_pool.buffers[i] = NULL;
        }
    }
    
    // 重置状态
    memset(&g_buffer_pool, 0, sizeof(g_buffer_pool));
}

/**
 * @brief 创建图像
 * 
 * @param image 图像结构体指针
 * @param width 图像宽度
 * @param height 图像高度
 * @param channels 图像通道数
 * @return int 成功返回0，失败返回-1
 */
int create_image(Image *image, int width, int height, int channels) {
    if (!image || width <= 0 || height <= 0 || channels <= 0 || channels > 4) {
        return -1;
    }
    
    // 分配图像数据
    unsigned char *data = (unsigned char *)malloc(width * height * channels);
    if (!data) {
        return -1;
    }
    
    // 初始化图像
    image->width = width;
    image->height = height;
    image->channels = channels;
    image->data = data;
    
    // 清零图像数据
    memset(data, 0, width * height * channels);
    
    return 0;
}

/**
 * @brief 销毁图像
 * 
 * @param image 图像结构体指针
 */
void destroy_image(Image *image) {
    if (image && image->data) {
        free(image->data);
        image->data = NULL;
        image->width = 0;
        image->height = 0;
        image->channels = 0;
    }
}

/**
 * @brief 分析图像，测量导线直径和覆冰厚度
 * 
 * @param src_image 输入图像
 * @param result 检测结果
 * @return int 成功返回0，失败返回-1
 */
int analyze_cable_image(const Image *src_image, CableDetection *result) {
    if (!g_image_processor.initialized) {
        log_message(LOG_LEVEL_ERROR, "图像处理: 未初始化");
        return -1;
    }
    
    if (!src_image || !src_image->data || !result) {
        log_message(LOG_LEVEL_ERROR, "图像处理: 无效的参数");
        return -1;
    }
    
    // 首先把结果初始化为无效状态
    result->detected = false;
    result->cable_diameter_pixels = 0.0f;
    result->cable_diameter_mm = 0.0f;
    result->ice_thickness_pixels = 0.0f;
    result->ice_thickness_mm = 0.0f;
    
    // 记录原始图像尺寸
    int orig_width = src_image->width;
    int orig_height = src_image->height;
    
    // 创建工作图像
    Image resized_image, gray_image, blurred_image, edge_image;
    if (create_image(&resized_image, orig_width / 2, orig_height / 2, src_image->channels) != 0 ||
        create_image(&gray_image, resized_image.width, resized_image.height, 1) != 0 ||
        create_image(&blurred_image, gray_image.width, gray_image.height, 1) != 0 ||
        create_image(&edge_image, gray_image.width, gray_image.height, 1) != 0) {
        log_message(LOG_LEVEL_ERROR, "图像处理: 创建工作图像失败");
        return -1;
    }
    
    // 缩小图像以加快处理速度
    if (!resize_image(src_image, &resized_image, resized_image.width, resized_image.height)) {
        log_message(LOG_LEVEL_ERROR, "图像处理: 调整图像大小失败");
        goto cleanup;
    }
    
    // 转换为灰度图
    grayscale_image(&resized_image, &gray_image);
    
    // 模糊处理
    blur_image(&gray_image, &blurred_image, g_config.blur_size);
    
    // 边缘检测/二值化
    if (!detect_edges(&blurred_image, &edge_image, g_config.threshold_value)) {
        log_message(LOG_LEVEL_ERROR, "图像处理: 边缘检测失败");
        goto cleanup;
    }
    
    // 查找轮廓
    ImageContour contours[MAX_CONTOURS];
    int num_contours = 0;
    if (!find_contours(&edge_image, contours, MAX_CONTOURS, &num_contours)) {
        log_message(LOG_LEVEL_ERROR, "图像处理: 查找轮廓失败");
        goto cleanup;
    }
    
    log_message(LOG_LEVEL_DEBUG, "图像处理: 找到 %d 个轮廓", num_contours);
    
    // 仅用于开发和调试 - 在克隆的源图像上绘制轮廓
    if (g_image_processor.debug_mode && num_contours > 0) {
        Image debug_image;
        if (create_image(&debug_image, resized_image.width, resized_image.height, resized_image.channels) == 0) {
            memcpy(debug_image.data, resized_image.data, resized_image.width * resized_image.height * resized_image.channels);
            
            // 调用draw_contours函数绘制轮廓，避免未使用警告
            Colour contour_color = {0, 255, 0, 255}; // 绿色
            draw_contours(&debug_image, contours, num_contours, contour_color);
            
            // ... 此处可以保存debug_image到文件系统 ...
            
            destroy_image(&debug_image);
        }
    }
    
    // 查找导线轮廓 - 通常是最长或面积最大的轮廓
    int best_contour_idx = -1;
    float best_contour_area = 0.0f;
    
    for (int i = 0; i < num_contours; i++) {
        float area = contours[i].area;
        
        // 排除太小或太大的轮廓
        if (area < g_config.min_contour_area || 
            area > g_config.max_contour_area) {
            continue;
        }
        
        if (area > best_contour_area) {
            best_contour_area = area;
            best_contour_idx = i;
        }
    }
    
    // 如果找到合适的轮廓
    if (best_contour_idx >= 0) {
        float width_pixels, height_pixels;
        
        if (measure_object(&contours[best_contour_idx], &width_pixels, &height_pixels)) {
            // 补偿因为缩小图像而减小的测量值
            width_pixels *= 2.0f;
            height_pixels *= 2.0f;
            
            // 设置结果
            result->detected = true;
            result->cable_diameter_pixels = width_pixels;
            result->cable_diameter_mm = width_pixels / g_config.pixels_per_mm;
            
            // 计算覆冰厚度 - 简单示例，实际可能需要更复杂的逻辑
            float expected_cable_width_pixels = g_config.cable_width_mm * g_config.pixels_per_mm;
            float ice_thickness_pixels = width_pixels - expected_cable_width_pixels;
            
            // 确保不是负数
            if (ice_thickness_pixels < 0.0f) {
                ice_thickness_pixels = 0.0f;
            }
            
            result->ice_thickness_pixels = ice_thickness_pixels;
            result->ice_thickness_mm = ice_thickness_pixels / g_config.pixels_per_mm;
            
            log_message(LOG_LEVEL_DEBUG, "图像处理: 导线直径 = %.2f pixels, %.2f mm",
                       result->cable_diameter_pixels, result->cable_diameter_mm);
            log_message(LOG_LEVEL_DEBUG, "图像处理: 覆冰厚度 = %.2f pixels, %.2f mm",
                       result->ice_thickness_pixels, result->ice_thickness_mm);
            
            // 可选: 在原始图像上绘制轮廓作为可视化
            // draw_contours(src_image, &contours[best_contour_idx], 1, (Colour){0, 255, 0, 255});
        }
    }
    
cleanup:
    // 清理工作图像
    destroy_image(&resized_image);
    destroy_image(&gray_image);
    destroy_image(&blurred_image);
    destroy_image(&edge_image);
    
    return result->detected ? 0 : -1;
}

/**
 * @brief 初始化图像处理器
 * 
 * @param config 图像处理配置
 * @return int 成功返回0，失败返回-1
 */
int init_image_processor(ImageProcessorConfig *config) {
    if (!config) {
        log_message(LOG_LEVEL_ERROR, "图像处理: 无效的配置参数");
        return -1;
    }
    
    // 复制配置
    memcpy(&g_config, config, sizeof(ImageProcessorConfig));
    
    // 初始化状态
    g_image_processor.initialized = true;
    g_image_processor.adaptive_threshold = true;  // 默认启用自适应阈值
    g_image_processor.dynamic_blur = true;        // 默认启用动态模糊
    g_image_processor.avg_light_level = 127.0f;   // 默认平均亮度
    g_image_processor.processing_level = 3;       // 默认最高处理级别
    
    // 初始化指数查找表
    init_exp_lut();
    
    // 初始化缓冲区池
    init_buffer_pool();
    
    log_message(LOG_LEVEL_INFO, "图像处理器: 初始化成功");
    return 0;
}

/**
 * @brief 清理图像处理器资源
 */
void cleanup_image_processor(void) {
    g_image_processor.initialized = false;
    cleanup_buffer_pool();  // 清理缓冲区池
    log_message(LOG_LEVEL_INFO, "图像处理器: 资源已清理");
}

/**
 * @brief 从文件加载图像
 * 
 * @param filename 图像文件路径
 * @param image 输出的图像结构体指针
 * @return int 成功返回0，失败返回-1
 */
int load_image_from_file(const char *filename, Image *image) {
    if (!filename || !image) {
        log_message(LOG_LEVEL_ERROR, "加载图像：无效的参数");
        return -1;
    }

#ifdef HAVE_OPENCV
    // 使用OpenCV加载图像
    unsigned char *data = NULL;
    int width = 0, height = 0, channels = 0;
    
    if (!opencv_load_image(filename, &data, &width, &height, &channels)) {
        log_message(LOG_LEVEL_ERROR, "无法加载图像：%s", filename);
        return -1;
    }

    // 创建输出图像
    if (create_image(image, width, height, channels) != 0) {
        log_message(LOG_LEVEL_ERROR, "无法创建图像结构");
        free(data);
        return -1;
    }

    // 复制数据
    memcpy(image->data, data, width * height * channels * sizeof(unsigned char));
    
    // 释放临时数据
    free(data);
    return 0;
#else
    // 非OpenCV版本，使用简单的方式加载图像
    FILE *file = fopen(filename, "rb");
    if (!file) {
        log_message(LOG_LEVEL_ERROR, "无法打开图像文件：%s", filename);
        return -1;
    }

    // 这里需要根据文件格式实现具体的解析逻辑
    // 由于这是一个复杂的任务，这里只是简单地返回错误
    log_message(LOG_LEVEL_ERROR, "非OpenCV版本不支持加载图像");
    
    fclose(file);
    return -1;
#endif
} 